package base.网络编程.UDP.聊天;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class 客户端一 {
    static volatile String otherIp = null;
    public static void main(String[] args) throws IOException {
        Rb t1 = new Rb();
        t1.setDaemon(true);
        t1.start();

        DatagramSocket ds = new DatagramSocket();//空参：随机端口发送

        Scanner sc = new Scanner(System.in);

        while (true) {
            System.out.println("---输入：");
            String str = sc.nextLine();
            if ("110".equals(str)){
                break;
            }
            //String str = "你好世界！！";
            byte[] bytes = str.getBytes();
            InetAddress ip = InetAddress.getByName(otherIp);
            DatagramPacket dp = new DatagramPacket(bytes,bytes.length,ip,10086);

            ds.send(dp);
        }
    }
}

class Rb extends Thread{
    @Override
    public void run() {
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(11111);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = new byte[1024];
        DatagramPacket dp = new DatagramPacket(bytes,bytes.length);

        while (true) {
            //解析数据包
            try {
                ds.receive(dp);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            byte[] data = dp.getData();
            int len = dp.getLength();
            InetAddress ip = dp.getAddress();
            String host = ip.getHostName();
            int port = dp.getPort();

            Pattern p = Pattern.compile("(\\d+\\.){3}\\d+");
            Matcher m = p.matcher(String.valueOf(ip));
            String matIp = null;
            if (m.find()){
                matIp = m.group();
            }
            客户端一.otherIp = String.valueOf(matIp);
            System.out.println("接收到来自"+ip+"的消息："+new String(data,0,len));
            System.out.println("对方端口号为："+port+",总共"+len+"个字节");
            if (new String(data,0,len).equals("我要连接你")){
                String s1 = "允许连接";
                bytes = s1.getBytes();
                try {
                    InetAddress ip1 = InetAddress.getByName(String.valueOf(matIp));
                    DatagramPacket dp1 = new DatagramPacket(bytes,bytes.length,ip1,11111);
                    ds.send(dp1);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

